#include "rewine/impl/CCustomImage.hpp"

using std::string;

namespace rewine {

CCustomImage::CCustomImage(const std::string& exportName) {
    setFullName("-");
    setExportName(exportName);
    setIsLoaded(true);
}

CCustomImage::list_t::iterator
CCustomImage::find(const std::string& symbolName) {
    return std::find_if(m_Exports.begin(), m_Exports.end(), [&symbolName](const CCustomImage::list_t::value_type &pEntry) {
        return pEntry->symbolName == symbolName;
    });
}

CCustomImage::list_t::const_iterator
CCustomImage::find(const std::string& symbolName) const {
    return std::find_if(m_Exports.cbegin(), m_Exports.cend(), [&symbolName](const CCustomImage::list_t::value_type &pEntry) {
        return pEntry->symbolName == symbolName;
    });
}

void
CCustomImage::set(const std::string& symbolName, std::shared_ptr<IExport> pExport) {
    auto it = find(symbolName);
    if (it != m_Exports.end()) {
        (*it)->pExport = std::move(pExport);
        return;
    }
    auto pEntry = std::make_shared<CCustomImageExportEntry>(symbolName, pExport);
    m_Exports.emplace_back(std::move(pEntry));
}

bool
CCustomImage::remove(const std::string& symbolName) {
    auto it = find(symbolName);
    if (it != m_Exports.end()) {
        m_Exports.erase(it);
        return true;
    }
    return false;
}

int
CCustomImage::getExportCount() const {
    return m_Exports.size();
}

IExport *
CCustomImage::getExportByIndex(unsigned int index) const {
    if (index < 0) return nullptr;
    int i = 0;
    for (auto pEntry : m_Exports) {
        if (i < index) {
            i++;
            continue;
        }
        return pEntry->pExport.get();
    }
    return nullptr;
}

IExport *
CCustomImage::getExportByName(const std::string& symbolName, uint16_t hint) const {
    auto it = find(symbolName);
    if (it != m_Exports.cend()) {
        return (*it)->pExport.get();
    }
    return nullptr;
}

} // namespace rewine
